from logging import raiseExceptions

# bytes reader related
class Reader(object):
    def __init__(self, gtp_bytes):
        self.__bytes = gtp_bytes if gtp_bytes is not None else bytes()
        self.__current = 0

    def __str__(self):
        return "cur:{},bytes:{}".format(self.__current, self.__bytes)

    def get(self, start, end):
        return self.__bytes[start:end]

    def peek(self):
        return self.__bytes[self.__current]

    def peekn(self, n):
        return self.__bytes[self.__current: self.__current+n]

    def next(self):
        curr_val = self.__bytes[self.__current]
        self.__current = self.__current + 1
        return  curr_val

    def eat(self):
        self.__current = self.__current + 1

    def eatn(self, n):
        self.__current = self.__current + n

    def position(self):
        return  self.__current

    def available(self):
        return  self.len() - self.__current

    def is_end(self):
        return self.__current == self.len()

    def len(self):
        return len(self.__bytes)

import unittest
from bcat.util.str import Str
class TestReader(unittest.TestCase):
    def test_main(self):
        bytes_str = 'X03=A100,M66=abc123'
        bytes_reader = Reader(Str(bytes_str).to_bytes("gbk"))
        print(bytes_reader)

        self.assertEqual(len(bytes_str), bytes_reader.len())

        print(ord(bytes_str[0]), bytes_reader.peek())
        self.assertEqual(ord(bytes_str[0]), bytes_reader.peek())
        self.assertTrue(bytes_reader.position() == 0)
        self.assertTrue(bytes_reader.available() == len(bytes_str))

        self.assertEqual(Str(bytes_str[0:2]).to_bytes("gbk"), bytes_reader.get(0,2))

        self.assertEqual(ord(bytes_str[0]), bytes_reader.next())
        self.assertTrue(bytes_reader.position() == 1)

        self.assertEqual(Str(bytes_str[1:3]).to_bytes("gbk"), bytes_reader.peekn(2))
        self.assertTrue(bytes_reader.position() == 1)

        bytes_reader.eat()
        self.assertTrue(bytes_reader.position() == 2)

        bytes_reader.eatn(len(bytes_str)-2)
        self.assertTrue(bytes_reader.is_end())

        pass


if __name__ == '__main__':
    unittest.main(verbosity=2)
